<?php
/**
 * order.php
 * User: yzm
 * Date: 2017/9/26
 */

class Order extends WebBase{
    public function __construct() {
        parent::__construct();
    }

    /*
     * 操作工单
     */
    public function create() {
        global $_W,$_GPC;
        load()->func('tpl');

        //所有的一级分类
        $category_list = pdo_getall('wherein_knowledge_category', array('uniacid' => $_W['uniacid'], 'parent_id' => 0), array('cat_id', 'cat_name'));

        //初次提交工单且后台管理没有回复的情况下可修改的数据
        if (!empty($_GPC['order_id'])) {
            $detail = pdo_get('wherein_knowledge_work_order', array('uniacid' => $_W['uniacid'], 'order_id' => $_GPC['order_id']));
            $detail['child_cat_name'] = empty($detail['child_cat_id']) ? '' : pdo_getcolumn('wherein_knowledge_category', array('cat_id' => $detail['child_cat_id']), 'cat_name');
            $detail['content'] = htmlspecialchars_decode($detail['content']);
            if (!empty($detail['pic'])) {
                $detail['pic'] = explode(IMG_IMPLODE, $detail['pic']);
            }
            //相关的二级分类
            $child_category_list = pdo_getall('wherein_knowledge_category', array('uniacid' => $_W['uniacid'], 'parent_id' => $detail['cat_id']), array('cat_id', 'cat_name'));
        }

        if ($_W['isajax']) {
            $data = array();
            if (empty($_GPC['cat_id']) || empty($_GPC['content'])) {
                $this->outjson(array('code' => 400, 'msg' => '参数不全'));
            }
            $data['uniacid'] = $_W['uniacid'];
            $data['order_sn'] = create_order_sn();
            $data['cat_id'] = $_GPC['cat_id'];
            $data['child_cat_id'] = !empty($_GPC['child_cat_id']) ? $_GPC['child_cat_id'] : 0;
            $data['openid'] = $_W['fans']['openid'];
            $data['nickname'] = $_W['fans']['nickname'];
            $data['content'] = htmlspecialchars(strip_tags($_GPC['content']));
            $data['pic'] = '';
            $pic = array();
            $pic = $this->uploadPic($_GPC['pic']);
            $data['pic'] = !empty($pic) ? implode(IMG_IMPLODE, $pic) : '';
            if (empty($_GPC['order_id'])) {
                $data['add_time'] = $_W['timestamp'];
            }
            $data['order_status'] = 0;
            $data['customer_status'] = 1;
            $data['unsolved_status'] = 0;//用户选择未解决时的子状态
            $data['is_reply'] = 0;//提问者
            $data['is_read'] = 1;//已读
            if (!empty($_GPC['order_id'])) {
                //修改工单
                $data['up_time'] = $_W['timestamp'];
                if (pdo_update('wherein_knowledge_work_order', $data, array('order_id' => $_GPC['order_id']))) {
                    $out['code'] = 200;
                    $out['msg'] = '提交工单成功';
                    $out['order_id'] = $_GPC['order_id'];
                } else {
                    $out['code'] = 304;
                    $out['msg'] = '提交工单失败';
                    $out['order_id'] = 0;
                }
            } else {
                if (pdo_insert('wherein_knowledge_work_order', $data)) {
                    $insert_id = pdo_insertid();
                    $cat_name = pdo_getcolumn('wherein_knowledge_category', array('cat_id' => $data['cat_id']), 'cat_name');
                    if (!empty($data['child_cat_id'])) {
                        $child_cat_name = pdo_getcolumn('wherein_knowledge_category', array('cat_id' => $data['child_cat_id']), 'cat_name');
                        $cat_name .= '-' . $child_cat_name;
                    }
                    $url = $_W['siteroot'] . 'app/' . $this->createMobileUrl('order', array('act' => 'waitingDetail', 'order_id' => $insert_id, 'read' => 1));
                    workorder_msg($_W['fans']['openid'], $cat_name, '', $url);

                    $out['code'] = 200;
                    $out['msg'] = '提交工单成功';
                    $out['order_id'] = $insert_id;
                } else {
                    $out['code'] = 304;
                    $out['msg'] = '提交工单失败';
                    $out['order_id'] = 0;
                }
            }
            $this->outjson($out);
        }

        //判断设备
        $device_type = get_device_type();

        include $this->template('create');
    }

    /*
     * 工单待回复详情 初次提交工单详情页面
     */
    public function waitingDetail() {
        global $_GPC,$_W;
        $detail = pdo_get('wherein_knowledge_work_order', array('uniacid' => $_W['uniacid'], 'order_id' => $_GPC['order_id']));
        if (empty($detail)) {
            message('没有找到相关数据', $this->createMobileUrl('index', array('act' => 'index')), 'error');
        }
        if ($detail['customer_status'] != 1) {
            header('Location: ' . $this->createMobileUrl('order', array('act' => 'replyDetail', 'order_id' => $detail['order_id'] , 'read' => 1)));
        }

        if (isset($_GPC['read']) && $_GPC['read'] == 1) {
            //改变为已读状态
            pdo_update('wherein_knowledge_work_order', array('is_read' => 1), array('order_id' => $_GPC['order_id']));
        }
        $detail['cat_name'] = pdo_getcolumn('wherein_knowledge_category', array('cat_id' => $detail['cat_id']), 'cat_name');
        $detail['child_cat_name'] = empty($detail['child_cat_id']) ? '' : pdo_getcolumn('wherein_knowledge_category', array('cat_id' => $detail['child_cat_id']), 'cat_name');
        $detail['content'] = htmlspecialchars_decode($detail['content']);
        if (!empty($detail['pic'])) {
            $detail['pic'] = explode(IMG_IMPLODE, $detail['pic']);
        }

        include $this->template('waitingDetail');
    }

    /*
     * 工单已回复详情
     */
    public function replyDetail() {
        global $_W,$_GPC;

        $detail = pdo_get('wherein_knowledge_work_order', array('uniacid' => $_W['uniacid'], 'order_id' => $_GPC['order_id']));
        if (empty($detail)) {
            message('没有找到相关数据', $this->createMobileUrl('index', array('act' => 'index')), 'error');
        }
        if (isset($_GPC['read']) && $_GPC['read'] == 1) {
            //改变为已读状态
            pdo_update('wherein_knowledge_work_order', array('is_read' => 1), array('order_id' => $_GPC['order_id']));
        }

        $detail['cat_name'] = pdo_getcolumn('wherein_knowledge_category', array('cat_id' => $detail['cat_id']), 'cat_name');
        $detail['child_cat_name'] = empty($detail['child_cat_id']) ? '' : pdo_getcolumn('wherein_knowledge_category', array('cat_id' => $detail['child_cat_id']), 'cat_name');
        $detail['content'] = htmlspecialchars_decode($detail['content']);

        $order_list = array();
        $order_list[] = array(
            'order_id' => $detail['order_id'],
            'belong_to' => 0,
            'parent_id' => $detail['parent_id'],
            'openid' => $detail['openid'],
            'nickname' => $detail['nickname'],
            'content' => $detail['content'],
            'pic' => $detail['pic'],
            'add_time' => format($detail['add_time'], 'Y-m-d H:i'),
            'is_reply' => $detail['is_reply'],
        );
        //查询相关的工单回复信息
        $order_reply_list = pdo_fetchall("SELECT order_id,belong_to,parent_id,openid,nickname,content,pic,add_time,is_reply FROM " . tablename('wherein_knowledge_work_order') . " WHERE uniacid = :uniacid AND belong_to = :belong_to ORDER BY order_id asc", array('uniacid' => $_W['uniacid'], ':belong_to' => $_GPC['order_id']));
        if (!empty($order_reply_list)) {
            foreach ($order_reply_list as $key => $value) {
                $value['add_time'] = format($value['add_time'], 'Y-m-d H:i');
                $order_list[] = $value;
            }
        }
        load()->model('mc');
        foreach ($order_list as $key => $value) {
            $user = mc_fansinfo($value['openid'], $_W['uniacid'], $_W['uniacid']);
            $order_list[$key]['avatar'] = !empty($user['avatar']) ? $user['avatar'] : NO_AVATAR;
            $order_list[$key]['content'] = htmlspecialchars_decode($value['content']);
            if (!empty($value['pic'])) {
                $order_list[$key]['pic'] = explode(IMG_IMPLODE, $value['pic']);
            }
        }

        //判断设备
        $device_type = get_device_type();

        include $this->template('replyDetail');
    }

    /*
     * 根据一级分类获取二级分类
     */
    public function getChildCate() {
        global $_GPC,$_W;

        $child_category_list = pdo_getall('wherein_knowledge_category', array('uniacid' => $_W['uniacid'], 'parent_id' => $_GPC['cat_id']), array('cat_id', 'cat_name'));
        $this->outjson(array('total' => count($child_category_list), 'child_category_list' => $child_category_list));
    }

    /*
     * 工单选择已解决
     */
    public function resolved() {
        global $_GPC;
        if (pdo_update('wherein_knowledge_work_order', array('order_status' => 1, 'customer_status' => 4), array('order_id' => $_GPC['order_id']))) {
            $out['code'] = 200;
            $out['msg'] = '您的问题选择已解决';
        } else {
            $out['code'] = 304;
            $out['msg'] = '更新数据失败';
        }
        $this->outjson($out);
    }

    /*
     * 工单选择未解决--不做更改
     */
    public function unresolved() {
        global $_GPC,$_W;
        if (pdo_update('wherein_knowledge_work_order', array('update_time' => $_W['timestamp'], 'order_status' => 0, 'customer_status' => 3, 'unsolved_status' => 2), array('order_id' => $_GPC['order_id']))) {
            $out['code'] = 200;
            $out['msg'] = '您的问题选择未解决';
        } else {
            $out['code'] = 304;
            $out['msg'] = '更新数据失败';
        }
        $this->outjson($out);
    }

    /*
     * 工单选择未解决--再次反馈
     */
    public function feedback() {
        global $_GPC, $_W;
        $order_data = pdo_get('wherein_knowledge_work_order', array('order_id' => $_GPC['order_id'], 'parent_id' => 0), array('order_id', 'parent_id', 'cat_id', 'child_cat_id', 'openid', 'nickname', 'add_time', 'order_status', 'customer_status', 'unsolved_status'));
        if (empty($order_data)) {
            $this->outjson(array('code' => 404, 'msg' => '找不到数据'));
        }

        if (in_array($order_data['customer_status'], array(1,3))) {
            $this->outjson(array('code' => 403, 'msg' => '你已反馈过该工单,请静待回复'));
        }

        //最后一次回复的管理工单id
        $parent_id = pdo_fetchcolumn("SELECT `order_id` FROM " . tablename('wherein_knowledge_work_order') . " WHERE `uniacid` = :uniacid AND `belong_to` = :belong_to AND `is_reply` = :is_reply ORDER BY order_id DESC ", array('uniacid' => $_W['uniacid'], ':belong_to' => $_GPC['order_id'], ':is_reply' => 1));

        $data = array();
        $data['order_sn'] = create_order_sn();
        $data['uniacid'] = $_W['uniacid'];
        $data['belong_to'] = $_GPC['order_id'];
        $data['parent_id'] = $parent_id ? $parent_id : $order_data['order_id'];
        $data['cat_id'] = $order_data['cat_id'];
        $data['child_cat_id'] = $order_data['child_cat_id'];
        $data['openid'] = $_W['fans']['openid'];
        $data['nickname'] = $_W['fans']['nickname'];
        $data['content'] = htmlspecialchars(strip_tags($_GPC['content']));
        $pic = array();
        $pic = $this->uploadPic($_GPC['pic']);
        $data['pic'] = !empty($pic) ? implode(IMG_IMPLODE, $pic) : '';
        $data['add_time'] = $_W['timestamp'];
        $data['is_reply'] = 0;

        if (pdo_insert('wherein_knowledge_work_order', $data)) {
            $insert_id = pdo_insertid();
            if (!pdo_update('wherein_knowledge_work_order', array('update_time' => $_W['timestamp'], 'order_status' => 0, 'customer_status' => 3, 'unsolved_status' => 1, 'expire_time' => ''), array('order_id' => $_GPC['order_id']))) {
                pdo_delete('wherein_knowledge_work_order', array('order_id' => $insert_id));
                $out['code'] = 304;
                $out['msg'] = '反馈失败: 无法更新数据';
                $this->outjson($out);
            }
            $this->outjson(array('code' => 200, 'msg' => '反馈成功', 'order_id' => $order_data['order_id']));
        } else {
            $out['code'] = 304;
            $out['msg'] = '反馈失败: 无法插入数据';
            $this->outjson($out);
        }
    }

    /*
     * 修改反馈信息
     */
    public function editFeedback() {
        global $_W,$_GPC;
        $data = array();
        if (empty($_GPC['order_id']) || empty($_GPC['content'])) {
            $this->outjson(array('code' => 400, 'msg' => '参数不全'));
        }
        $data['content'] = htmlspecialchars(strip_tags($_GPC['content']));
        if (!empty($_GPC['pic']) && count($_GPC['pic']) > 8) {
            $this->outjson(array('code' => 302, 'msg' => '最多只能上传8张图片'));
        }
        $pic = array();
        $pic = $this->uploadPic($_GPC['pic']);
        $data['pic'] = !empty($pic) ? implode(IMG_IMPLODE, $pic) : '';
        $data['up_time'] = $_W['timestamp'];

        $res = pdo_update('wherein_knowledge_work_order', $data, array('order_id' => $_GPC['order_id']));
        //修改
        if (!empty($res)) {
            $out['code'] = 200;
            $out['msg'] = '修改成功';
        } else {
            $out['code'] = 304;
            $out['msg'] = '修改失败';
        }
        $this->outjson($out);
    }

    /*
     * 删除图片:删除本地
     */
    public function delPic() {
        global $_GPC,$_W;

        $order_data = pdo_get('wherein_knowledge_work_order', array('uniacid' => $_W['uniacid'], 'order_id' => $_GPC['order_id']), array('order_id', 'pic'));
        if (empty($order_data)) {
            $this->outjson(array('code' => 400, 'msg' => '删除图片失败'));
        }

        load()->func('file');
        $result = file_delete($_GPC['pic']);
        if (!is_error($result)) {
            //删除图片成功后更新数据库
            $arr_pic = explode(IMG_IMPLODE, $order_data['pic']);
            if (!empty($arr_pic)) {
                foreach ($arr_pic as $key => $val) {
                    if ($_GPC['pic'] === $val) {
                        unset($arr_pic[$key]);
                    }
                }
                $pic = implode(IMG_IMPLODE, $arr_pic);
                pdo_update('wherein_knowledge_work_order', array('pic' => $pic), array('uniacid' => $_W['uniacid'], 'order_id' => $_GPC['order_id']));
            }
        } else {
            $this->outjson(array('code' => 400, 'msg' => '删除图片失败'));
        }
    }

    /*
     * 获取
     */
    public function get_reply_data() {
        global $_GPC;
        //再次修改反馈信息
        $edit_reply_data = pdo_fetch("SELECT order_id,content,pic FROM " . tablename('wherein_knowledge_work_order') . " WHERE belong_to = :belong_to AND is_reply = :is_reply ORDER BY order_id DESC ", array(':belong_to' => $_GPC['order_id'], ':is_reply' => 0));
        $detail = array();
        if (!empty($edit_reply_data)) {
            $detail['reply_order_id'] = $edit_reply_data['order_id'];
            $detail['reply_content'] = $edit_reply_data['content'];
            if (!empty($edit_reply_data['pic'])) {
                $detail['reply_pic'] = explode(IMG_IMPLODE, $edit_reply_data['pic']);
                foreach ($detail['reply_pic'] as $k => $v) {
                    $detail['reply_pic'][$k] = array(
                        'reply_pic' => $v,
                        'reply_pic_tomedia' => tomedia($v),
                    );
                }
            }
            $this->outjson(array('code' => 200, 'data' => $detail));
        } else {
            $this->outjson(array('code' => 404, 'data' => $detail));
        }
    }

    /*
     * 上传图片返回路径
     * @params $pic_list
     * return array()
     */
    private function uploadPic($pic_list = array()) {
        global $_W;
        $pic = array();
        if (empty($pic_list)) {
            return $pic;
        }
        load()->func('file');
        $uniacid = intval($_W['uniacid']);
        $path = "images/{$uniacid}/" . date('Y/m/');
        mkdirs(ATTACHMENT_ROOT . '/' . $path);
        foreach ($pic_list as $key => $value) {
            if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $value, $result)){
                $ext = $result[2];
                $filename = file_random_name(ATTACHMENT_ROOT . '/' . $path, $ext);
                $fullname = ATTACHMENT_ROOT . '/' . $path . $filename;

                if (file_put_contents($fullname, base64_decode(str_replace($result[1], '', $value)))){
                    $pic[] = $path . $filename;
                }
            } else {
                $pic[] = $value;
            }
        }
        return $pic;
    }


}